package com.sp.model.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * spring security所需实体
 *
 * @author tong
 * @date 2024/4/13 8:09
 */
@Data
@NoArgsConstructor
public class EmployeeDetails implements UserDetails, Serializable {

    private static final long serialVersionUID = 1L;

    private Employee employee;

    private List<EmployeeRole> employeeRoles;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }

        //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
        authorities = new ArrayList<>();
        for (EmployeeRole employeeRole : employeeRoles) {
            authorities.add(new SimpleGrantedAuthority(employeeRole.getKeyword()));
            List<Permission> permissions = employeeRole.getPermissions();
            for (Permission permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        return authorities;
    }

    @Override
    public String getUsername() {
        return this.employee.getUsername();
    }

    @Override
    public String getPassword() {
        return this.employee.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
